//
//  19. 删除链表的倒数第N个结点.swift
//  LeetCodeTrain
//
//  Created by rjb on 2021/5/20.
//  Copyright © 2021 rjb. All rights reserved.
//

import Foundation
class Solution19 {
    func removeNthFromEnd(_ head: ListNode?, _ n: Int) -> ListNode? {
        let vHead = ListNode(-1)
        vHead.next = head
        
        var p1:ListNode? = vHead
        var p = head
        var m = n
        
        while p != nil {
            if m <= 0 {
                p1 = p1?.next
            }
            m -= 1
            p = p?.next
        }
        p1?.next = p1?.next?.next
        return vHead.next
    }
    static func test(){
        let node1 = ListNode(1)
        let node2 = ListNode(2)
        let node3 = ListNode(3)
        let node4 = ListNode(4)
        let node5 = ListNode(5)
        
        node1.next = node2
        node2.next = node3
        node3.next = node4
        node4.next = node5
        
        let solution = Solution19()
        let result = solution.removeNthFromEnd(node1, 2)
        print(result)
    }
}
